
const app = getApp()
Page({
    data: {
      remote_src: app.globalData.remote_src,
      selectedImages: [],
      maxImages: 9,
      currentTab: 'other',
      selectedPeople: '3',
      selectedCost: 'free',
      selectedType: '拍照',
      title: '',
      locationInfo: null,  // 存储完整的位置信息
      days: [],
      showTimePicker: false,
      showEndTimePicker: false,
      dialogButtons: [{text: '下一步'}], 
      endDialogButtons: [{text: '确定'}],
      startTimeText: '',
      endTimeText: '',
      timeText: '时间',
      hours: Array.from({length: 24}, (_, i) => String(i).padStart(2, '0')),
      minutes: Array.from({length: 60}, (_, i) => String(i).padStart(2, '0')),
      timePickerValue: [0, 0, 0],
      showActivityType: false,
      activityTypes: [
        { name: '拍照', selected: false },
        { name: '探店', selected: false },
        { name: '约饭', selected: false },
        { name: '爬山', selected: false },
        { name: '露营', selected: false },
        { name: '户外', selected: false },
        { name: '运动', selected: false },
        { name: '做美甲', selected: false },
        { name: '看电影', selected: false },
        { name: '逛街', selected: false },
        { name: '旅游', selected: false },
        { name: '看展', selected: false },
        { name: '撸猫撸狗', selected: false },
        { name: '其他', selected: false }
      ],
      showPeopleInput: false,
      inputPeople: '',
      other_configs: [
        {
          title: '在线求搭子一起玩耍啦🎉',
          content: '有没有姐妹想找个长期搭子啊？周末节假日都能约，时间对得上就行！可以一起干饭发呆探店，本i人超好相处，熟了还能一起旅游～✨'
        },
        {
          title: '寻找志同道合的小伙伴💫',
          content: '想找个能聊得来的搭子，一起分享生活中的小确幸。可以约看电影、逛展览、喝下午茶，或者就是简单地一起发呆聊天都很棒～期待遇见有趣的你！'
        },
        {
          title: '约个有趣的灵魂一起探索世界🌟',
          content: '生活需要一些新鲜感！找个同样热爱生活的搭子，一起去发现城市里的小惊喜，无论是隐藏的小店还是有趣的活动，让我们一起创造美好回忆吧～'
        }
      ],
      photo_configs: [
        {
          title: '在线求拍照搭子，记录日常点滴✨',
          content: '姐妹们，有没有喜欢拍照的搭子？找个能一起捕捉生活美好的你，无论是街拍还是风景，一起留下我们的足迹📸👣'
        },
        {
          title: '寻找摄影小伙伴，定格美好瞬间📷',
          content: '想找个一起拍照的姐妹！可以互相当模特，也可以一起练习摄影技巧。从日常街拍到主题写真，让我们用镜头记录青春的美好时光～'
        },
        {
          title: '约拍搭子，一起发现生活中的美✨',
          content: '热爱拍照的姐妹看过来！想找个审美在线的搭子，一起去各种好看的地方打卡拍照。咖啡厅、公园、艺术馆...到处都是我们的摄影棚！'
        }
      ],
      sport_configs: [
        {
          title: '约运动搭子，一起动起来💪',
          content: '找个运动小伙伴一起锻炼！可以约跑步、瑜伽、健身房，或者一起打球都可以～互相监督、互相鼓励，让运动变得更有趣。'
        },
        {
          title: '寻找健身伙伴，一起挥汗如雨🏃‍♀️',
          content: '想要坚持运动但总是缺乏动力？来找个运动搭子吧！可以一起制定健身计划，互相打卡监督，让运动成为一种快乐的习惯～'
        },
        {
          title: '约个运动达人，一起享受运动的快乐🎾',
          content: '运动使人快乐！想找个同样热爱运动的搭子，一起尝试各种运动项目。从基础的跑步到有趣的攀岩，让我们一起探索运动的无限可能！'
        }
      ],
      shopping_configs: [
        {
          title: '约逛街搭子，一起买买买🛍️',
          content: '找个一起逛街的姐妹！可以一起淘宝、交流穿搭心得、分享购物经验。不管是血拼还是随便逛逛都可以，重要的是有个人陪着一起享受购物的快乐～'
        },
        {
          title: '寻找购物小伙伴，一起发现好物💄',
          content: '购物路上不孤单！想找个有共同审美的搭子，一起逛商场、淘好货。可以互相参考意见，分享优惠信息，让购物变得更有趣更划算～'
        },
        {
          title: '约个时尚达人，一起追求美丽👗',
          content: '时尚是一种态度！找个同样爱美的搭子，一起研究穿搭、分享美妆心得。从服装到配饰，让我们一起变得更美更自信！'
        }
      ],
      food_configs: [
        {
          title: '约饭搭子，一起探索美食🍜',
          content: '寻觅一起分享美食的搭子！无论是探店打卡还是简单聚餐，美食和好心情都要一起分享。我是个地道的吃货，最近发现了好多有趣的餐厅～'
        },
        {
          title: '寻找美食伙伴，一起品味人生🍰',
          content: '美食是生活的调味剂！想找个同样热爱美食的搭子，一起去尝试各种料理。从街边小吃到精致餐厅，让我们的味蕾一起去旅行～'
        },
        {
          title: '约个吃货朋友，一起享受美味时光🥘',
          content: '吃货的快乐需要分享！找个能一起品尝美食的搭子，可以一起做饭、一起探店、一起研究新菜谱。让我们用美食连接彼此的心～'
        }
      ],
      // 当前文案索引
      currentConfigIndex: {
        other: 0,
        photo: 0,
        sport: 0,
        shopping: 0,
        food: 0
      },
    
     
    },
    // 添加点击"帮我写"的处理函数
    writeForMe(e) {
      const type = e.currentTarget.dataset.type; // title 或 content
      const currentTab = this.data.currentTab;
      const configKey = `${currentTab}_configs`;
      const configs = this.data[configKey];
      
      if (!configs || configs.length === 0) return;
      
      // 获取当前索引并切换到下一个
      let currentIndex = this.data.currentConfigIndex[currentTab];
      currentIndex = (currentIndex + 1) % configs.length;
      
      // 更新当前索引
      const newConfigIndex = { ...this.data.currentConfigIndex };
      newConfigIndex[currentTab] = currentIndex;
      
      // 获取新的文案
      const newConfig = configs[currentIndex];
      
      // 根据点击的类型更新对应的内容
      const updateData = {
        currentConfigIndex: newConfigIndex
      };
      
      if (type === 'title') {
        updateData.title = newConfig.title;
      } else if (type === 'content') {
        updateData.content = newConfig.content;
      } else {
        // 如果没有指定类型，同时更新标题和内容
        updateData.title = newConfig.title;
        updateData.content = newConfig.content;
      }
      
      this.setData(updateData);
      
      // 显示提示
      wx.showToast({
        title: `已切换到第${currentIndex + 1}个文案`,
        icon: 'none',
        duration: 1000
      });
    },
    // 显示人数输入框
    showPeopleInput() {
      this.setData({
        showPeopleInput: true
      });
    },

    // 关闭人数输入框
    closePeopleInput() {
      this.setData({
        showPeopleInput: false
      });
    },
    // 监听人数输入
    onPeopleInput(e) {
      this.setData({
        inputPeople: e.detail.value
      });
    },

    // 确认人数选择
    confirmPeople() {
      if (this.data.inputPeople) {
        this.setData({
          selectedPeople: this.data.inputPeople,
          showPeopleInput: false
        });
      }
    },

    // 显示更多活动类型
    showMoreTypes() {
      this.setData({
        showActivityType: true
      });
    },
      // 关闭活动类型选择框
    closeActivityType() {
      this.setData({
        showActivityType: false
      });
    },

  // 选择活动类型
  selectActivityType(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    const types = this.data.activityTypes.map((item, idx) => ({
      ...item,
      selected: idx === index
    }));
    
    this.setData({
      activityTypes: types,
      selectedType: type
    });
  },

  // 确认活动类型选择
  confirmActivityType() {
    const selectedType = this.data.activityTypes.find(type => type.selected);
    if (selectedType) {
      this.setData({
        selectedType: selectedType.name,
        showActivityType: false
      });
    }
  },
  loadDate(){
     // 生成未来7天的日期
     const days = [];
     const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
     const now = new Date();
     
     for(let i = 0; i < 7; i++) {
       const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000);
       const month = date.getMonth() + 1;
       const day = date.getDate();
       const weekday = weekdays[date.getDay()];
       days.push(`${month}月${day}日 ${weekday}`);
     }
     
     this.setData({ days });
    //  if(options.type) {
    //    switch(options.type) {
    //      case '1':
    //        this.data.currentTab = 'photo';
    //        break;
    //      case '2':
    //        this.data.currentTab = 'activity';
    //        break;
    //      case '3':
    //        this.data.currentTab = 'shopping';
    //        break;
    //      default:
    //        this.data.currentTab = 'other';
    //        break;
    //    } 
    //  }
  },
  onLoad(options) {
    // 解析配置信息

    let tab = 'other'
    if(options.id === '1') {
      tab = 'photo';
    }else if(options.id === '2') {
      tab = 'sport';
    }else if(options.id === '3') {
      tab = 'shopping';
    }else {
      tab = 'other'; 
    }
    console.log(options.id, tab);
    this.switchTab({
      currentTarget: {
        dataset: {
          tab: tab
        }
      } 
    })
    this.loadDate();
  },
  
  chooseLocation() {
      wx.chooseLocation({
        success: (res) => {
          console.log('选择地址成功', res);
          this.setData({
            locationInfo: {
              name: res.name,
              address: res.address,
              latitude: res.latitude,
              longitude: res.longitude
            }
          });
        },
        fail: (err) => {
          console.log('选择地址失败', err);
        }
      });
    },
    chooseTime() {
      this.setData({
        showTimePicker: true
      });
    },
    onTimePickerChange(e) {
      console.log('选择时间');
      const val = e.detail.value;
      this.setData({
        timePickerValue: val
      });
    },
  
    onStartTimePickerAction(e) {
      const { days, hours, minutes, timePickerValue } = this.data;
      // 解析日期字符串，例如："1月1日 周一"
      const dayStr = days[timePickerValue[0]];
      const matches = dayStr.match(/(\d+)月(\d+)日/);
      const currentYear = new Date().getFullYear();
      
      // 构建完整的日期时间字符串
      const selectedTime = `${currentYear}-${String(matches[1]).padStart(2, '0')}-${String(matches[2]).padStart(2, '0')} ${hours[timePickerValue[1]]}:${minutes[timePickerValue[2]]}:00`;
      
      this.setData({
        startTimeText: selectedTime,
        showTimePicker: false,
        showEndTimePicker: true
      });
    },

    onEndTimePickerAction(e) {
      const { days, hours, minutes, timePickerValue } = this.data;
      // 解析日期字符串
      const dayStr = days[timePickerValue[0]];
      const matches = dayStr.match(/(\d+)月(\d+)日/);
      const currentYear = new Date().getFullYear();
      
      // 构建完整的日期时间字符串
      const selectedTime = `${currentYear}-${String(matches[1]).padStart(2, '0')}-${String(matches[2]).padStart(2, '0')} ${hours[timePickerValue[1]]}:${minutes[timePickerValue[2]]}:00`;
      
      this.setData({
        endTimeText: selectedTime,
        showEndTimePicker: false,
        timeText: `${this.data.startTimeText.split(':').slice(0, 2).join(':')} - ${selectedTime.split(':').slice(0, 2).join(':')}`
      });
    },
    // 修改 switchTab 函数
    switchTab(e) {
      const tab = e.currentTarget.dataset.tab;
      console.log(tab);
      if (tab) {
        // 获取对应配置
        const configKey = `${tab}_configs`;
        const configs = this.data[configKey];
        const currentIndex = this.data.currentConfigIndex[tab] || 0;
        
        let title = '';
        let content = '';
        let selectedType = '';
        
        if (configs && configs.length > 0) {
          title = configs[currentIndex].title;
          content = configs[currentIndex].content;
        }
        
        // 设置对应的活动类型
        if(tab === 'photo') {
          selectedType = '拍照';
        } else if(tab === 'sport') {
          selectedType = '运动';
        } else if(tab === 'shopping') {
          selectedType = '逛街';
        } else if(tab === 'food') {
          selectedType = '约饭';
        } else {
          selectedType = '其他';
        }
        
        // 更新活动类型的选中状态
        const types = this.data.activityTypes.map(item => ({
          ...item,
          selected: item.name === selectedType
        }));
        
        this.setData({
          title: title || '',
          content: content || '',
          currentTab: tab || 'other',
          selectedType: selectedType,
          activityTypes: types
        });
      }
    },
    selectPeople(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedPeople: value });
    },
  
    selectCost(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedCost: value });
    },
  
    selectType(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedType: value });
    },
  
    onTitleInput(e) {
      this.setData({ title: e.detail.value });
    },
    onContentInput(e) {
      this.setData({ content: e.detail.value });
    },
    chooseImage() {
      const remainCount = this.data.maxImages - this.data.selectedImages.length;
      if (remainCount <= 0) {
        wx.showToast({
          title: '最多选择9张图片',
          icon: 'none'
        });
        return;
      }
      wx.chooseImage({
        count: remainCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // const newImages = [...this.data.selectedImages, ...res.tempFilePaths];
          // this.setData({
          //   selectedImages: newImages
          // });
          // 上传图片到服务器
          this.uploadImages(res.tempFilePaths);
        }
      });
    },
        // 添加上传图片方法
    uploadImages(tempFilePaths) {
          wx.showLoading({
            title: '上传图片中...',
            mask: true
          });
          const uploadPromises = tempFilePaths.map(path => {
            return new Promise((resolve, reject) => {
              const url = getApp().globalData.onlineService + '/api/infra/file';
              wx.uploadFile({
                url: url,
                filePath: path,
                name: 'file',
                success: res => {
                  const data = JSON.parse(res.data);
                  console.log(data);
                  if (data.code === 200) {
                    resolve(url + "?filename=" + data.filename);
                  } else {
                    reject(new Error(data.msg || '上传失败'));
                  }
                },
                fail: err => reject(err)
              });
            });
          });
          Promise.all(uploadPromises)
            .then(urls => {
              const newImages = [...this.data.selectedImages, ...urls];
              this.setData({
                selectedImages: newImages
              });
              wx.hideLoading();
            })
            .catch(err => {
              console.error('上传图片失败：', err);
              wx.hideLoading();
              wx.showToast({
                title: '上传图片失败',
                icon: 'none'
              });
            });
    },
    // 添加图片预览函数
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const current = this.data.selectedImages[index];
    
    wx.previewImage({
      current: current, // 当前显示图片的链接
      urls: this.data.selectedImages // 需要预览的图片链接列表
    });
  },

    // Add this function to delete images
    deleteImage(e) {
        const index = e.currentTarget.dataset.index;
        const newImages = this.data.selectedImages.filter((_, i) => i !== index);
        this.setData({
          selectedImages: newImages
        });
    },
    publishActivity() {
      // 数据验证
      if (!this.data.title.trim()) {
        wx.showToast({
          title: '请输入活动标题',
          icon: 'none'
        });
        return;
      }

      if (this.data.selectedImages.length === 0) {
        wx.showToast({
          title: '请至少上传一张图片',
          icon: 'none'
        });
        return;
      }

      if (!this.data.locationInfo) {
        wx.showToast({
          title: '请选择活动地点',
          icon: 'none'
        });
        return;
      }

      if (this.data.timeText === '时间') {
        wx.showToast({
          title: '请选择活动时间',
          icon: 'none'
        });
        return;
      }

      // 显示加载提示
      wx.showLoading({
        title: '发布中...',
        mask: true
      });

      // 构建活动数据
      const activityData = {
        name: this.data.title,
        content: this.data.content,
        images: this.data.selectedImages,
        type: this.data.selectedType,
        address_name: this.data.locationInfo.address,
        address: this.data.locationInfo.name,
        longitude: this.data.locationInfo.longitude,
        latitude: this.data.locationInfo.latitude,
        start_time: this.data.startTimeText,
        end_time: this.data.endTimeText,
        people_number: this.data.selectedPeople,
        fee: this.data.selectedCost,
      };
      const token = getApp().globalData.userInfo.token;
      console.log(token);
      const requset_url = getApp().globalData.onlineService + '/api/activity/activity';
      wx.request({
        url:  requset_url,
        method: 'POST',
        header: {
          'Authorization': 'Bearer '+ token,
          'content-type': 'application/json'
        },
        data: activityData,
        success: (res) => {
          wx.hideLoading();
          console.log('发布活动成功：', res.data);
          if (res.data.code === 200) {
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 2000
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 2000);
          } else {
            wx.showToast({
              title: res.data.msg || '发布失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          console.error('发布活动失败：', err);
        }
      });
      
    }
  });